package com.mrjy.live.bo;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alipay.util.AlipayNotify;
import com.mrjy.common.entity.WisPayment;
import com.mrjy.common.entity.OrderInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.WisLessonInfo;
import com.mrjy.common.entity.WisSign;
import com.mrjy.common.util.CharSetUtil;
import com.mrjy.common.util.DateUtil;
import com.mrjy.live.dao.IWisLessonInfoDao;
import com.mrjy.live.dao.IWisPaymentDao;
import com.mrjy.live.dao.IWisSignDao;
import com.tencent.protocol.pay_protocol.ScanPayResData;

@Service("wisPaymentBo")
public class WisPaymentBo implements IWisPaymentBo{
	@Resource
	private IWisPaymentDao wisPaymentDao;
	@Resource
	private IWisLessonInfoDao wisLessonInfoDao;
	@Resource
	private IWisSignDao wisSignDao;
	
	
	@Override
	public Object addPayment(WisPayment wisPayment) {		
		WisLessonInfo lessonInfo = wisLessonInfoDao.queryIdByCode(wisPayment.getLessonCode());
		wisPayment.setLiveInfoId(lessonInfo.getId());
		//wisPayment.setLiveInfoId(lessonInfo.getId());
		WisPayment existPayment = wisPaymentDao.queryPayment(wisPayment);
		if(existPayment != null) return "ok";
		int addCount = wisPaymentDao.insert(wisPayment);
		if(addCount > 0){
			return "ok";
		}
		return null;
	}
	@Override
	public Object deletePayment(WisPayment wisPayment) {
		int addCount = wisPaymentDao.deleteByUserAndLesson(wisPayment);
		if(addCount > 0){
			return "ok";
		}
		return null;
	}
	@Override
	public Object queryPayment(WisPayment wisPayment, UserInfo userInfo) {		
			WisLessonInfo wisLessonInfo = wisLessonInfoDao.queryByLessonCode(wisPayment.getLessonCode());
			if(wisLessonInfo != null){
				if(userInfo.getRoleId() == 2 || wisLessonInfo.getPrice() <= 0){
					return "ok";
				}
				wisPayment.setLiveInfoId(wisLessonInfo.getId());
				wisPayment.setUserId(userInfo.getId());
				WisPayment existPayment = wisPaymentDao.queryPayment(wisPayment);
				if(existPayment != null){
					return "ok";
				}
			}	
		return "error";
	}
	@Override
	public Object beginPayment(WisPayment wisPayment, UserInfo userInfo) {
		
			WisLessonInfo wisLessonInfo = wisLessonInfoDao.queryByLessonCode(wisPayment.getLessonCode());
			if(wisLessonInfo != null){
				wisPayment.setName(wisLessonInfo.getLessonName());
				wisPayment.setLiveInfoId(wisLessonInfo.getId());
				wisPayment.setMoney(wisLessonInfo.getPrice());
				wisPayment.setPrice(wisPayment.getMoney());
				
				StringBuffer sbHtml = new StringBuffer();
				sbHtml.append("<form id=\"orderForm\" action=\"live/wisPayment/submitPayment.do\" method=\"POST\">");
				sbHtml.append("<input type=\"hidden\" name=\"liveInfoId\" value=\"" + wisPayment.getLiveInfoId() + "\"/>");
				sbHtml.append("<input type=\"hidden\" name=\"name\" value=\"" + wisPayment.getName() + "\"/>");
				sbHtml.append("<input type=\"hidden\" name=\"money\" value=\"" + wisPayment.getMoney() + "\"/>");
				sbHtml.append("</form>");
				wisPayment.setHtml(sbHtml.toString());
				wisPayment.setMessageString("success");
				return wisPayment;
			}	
		return null;
	}
	@Override
	public Object submitPayment(WisPayment wisPayment, UserInfo userInfo) {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		wisPayment.setName(CharSetUtil.toUTF8(wisPayment.getName()));
		if (userInfo == null) {
			wisPayment.setMessageString("userInfo_error");
			return wisPayment;
		} else {
			wisPayment.setUserId(userInfo.getId());
			WisPayment existLivePayment = wisPaymentDao.queryWaitingPayment(wisPayment);
			Date now = wisPaymentDao.getTime();
			if (existLivePayment == null) {
				wisPayment.setCode("wis_" + userInfo.getId() + "_"
						+ wisPayment.getLiveInfoId() + "_" + df.format(now));
				wisPayment.setOrderTime(now);
				wisPayment.setDescription(wisPayment.getName());
				wisPayment.setStatusId(1);
				int rows = wisPaymentDao.insertSelective(wisPayment);
				if (rows != 1) {
					wisPayment.setMessageString("update_error");
				}
				wisPayment.setUrl("live/wisPayment/getPaymentByCode.do?code▲"+wisPayment.getCode());
				return wisPayment;
			} else {

                WisPayment oldLivePayment = new WisPayment();
				oldLivePayment.setId(existLivePayment.getId());
				oldLivePayment.setCode("wis_" + userInfo.getId() + "_"
						+ wisPayment.getLiveInfoId() + "_" + df.format(now));
				oldLivePayment.setOrderTime(now);
				oldLivePayment.setMoney(wisPayment.getMoney());
				int rows = wisPaymentDao.updateByPrimaryKeySelective(oldLivePayment);
				if (rows != 1) {
					oldLivePayment.setMessageString("update_error");
				}
				oldLivePayment.setUrl("live/wisPayment/getPaymentByCode.do?code▲"+oldLivePayment.getCode());
				return oldLivePayment;
			}
		}
	}
	@Override
	public Object getPaymentByCode(String code) {
		WisPayment livePaymentCheck = wisPaymentDao.selectByCode(code);
		if (livePaymentCheck == null) {
			livePaymentCheck = new WisPayment();
			livePaymentCheck.setCode(code);
			livePaymentCheck.setMessageString("fail");
			livePaymentCheck.setUrl("live/wisPayment/validatePay.do?code="+livePaymentCheck.getCode());
			return livePaymentCheck;
		} else {
			livePaymentCheck.setMessageString("success");
			livePaymentCheck.setUrl("live/wisPayment/validatePay.do?code="+livePaymentCheck.getCode());
			return livePaymentCheck;
		}
	}
	@Override
	public Object validatePay(String code) {
		WisPayment livePaymentCheck = wisPaymentDao.selectByCode(code);
		if (livePaymentCheck == null) {
			livePaymentCheck = new WisPayment();
			livePaymentCheck.setCode(code);
			livePaymentCheck.setMessageString("fail");
			return livePaymentCheck;
		} else {
			if (livePaymentCheck.getStatusId().intValue() == 2) {
				livePaymentCheck.setHtml("你购买的课程已经成功付款,请返回刷新查看。<a id='submitorder' class='btn btn-success' href='#'>支付完成</a>");
				livePaymentCheck.setMessageString("success");
				return livePaymentCheck;
			} else {
				livePaymentCheck.setMessageString("fail");
				livePaymentCheck.setReturn_url("live/wisPayment/returnUrl.do");
				livePaymentCheck.setNotify_url("live/wisPayment/notifyUrl.do");
				livePaymentCheck.setWxnotify_url("live/wisPayment/WXnotifyUrl.do");
				livePaymentCheck.setClassName("wisPaymentBo");
				return livePaymentCheck;
			}
		}
	}
	
	@Override
	public WisPayment returnUrl(Map<String, String>params,String out_trade_no,String trade_no,String trade_status,Float money) {
		// 先本地检查，看是否已经支付成功
		WisPayment livePaymentCheck = wisPaymentDao.selectCompleteByCode(out_trade_no);
	    if (livePaymentCheck != null) {
	    	livePaymentCheck.setUrl("live/wisPayment/validatePay.do?code▲"+out_trade_no);
	    	livePaymentCheck.setMessageString("payment/payment_success");
			return livePaymentCheck;
		}
		// 计算得出通知验证结果
		boolean verify_result = true;//AlipayNotify.verify(params);

		WisPayment livePaymentExist = wisPaymentDao.selectByCode(out_trade_no);
		
		if (verify_result) {// 验证成功
			if (trade_status.equals("TRADE_FINISHED")|| trade_status.equals("TRADE_SUCCESS")) {
				if (livePaymentExist == null) {
					livePaymentExist = new WisPayment();
					livePaymentExist.setUrl("live/wisPayment/validatePay.do?code▲"+out_trade_no);
					livePaymentExist.setMessageString("payment/payment_fail");
					return livePaymentExist;
				}
				livePaymentExist.setUrl("live/wisPayment/validatePay.do?code▲"+out_trade_no);
				if (livePaymentExist.getMoney().floatValue() != money.floatValue()) {
					livePaymentExist.setMessageString("payment/payment_fail");
					return livePaymentExist;
				}
				WisPayment livePaymentUpdate = new WisPayment();
				livePaymentUpdate.setId(livePaymentExist.getId());
				livePaymentUpdate.setCompletionTime(wisPaymentDao.getTime());
				livePaymentUpdate.setStatusId(2);
				livePaymentUpdate.setPaymentMethod("alipay");
				livePaymentUpdate.setTradeNo(trade_no);
				int rows = wisPaymentDao.updateByPrimaryKeySelective(livePaymentUpdate);
				if (rows != 1) {
					livePaymentExist.setMessageString("payment/payment_fail");
					return livePaymentExist;
				}else{
					WisSign wisSign=new WisSign();
					wisSign.setWisLessonId(livePaymentExist.getLiveInfoId());
					wisSign.setUserId(livePaymentExist.getUserId());
					wisSign.setRegisterTime(DateUtil.dateToString(new Date(), 2));
					wisSign.setDisableFlag(0);
					int rowss=wisSignDao.insert(wisSign);
					if(rowss!=1){
						livePaymentExist.setMessageString("payment/payment_fail");
						return livePaymentExist;
					}
				}
				livePaymentExist.setMessageString("payment/payment_success");
			}else {
				livePaymentExist.setMessageString("payment/payment_fail");
			}
			return livePaymentExist;
		} else {
			if (livePaymentExist == null) {
				livePaymentExist = new WisPayment();
			}
			livePaymentExist.setUrl("live/wisPayment/validatePay.do?code▲"+out_trade_no);
			livePaymentExist.setMessageString("payment/payment_fail");
			return livePaymentExist;
		}
	}
	@Override
	public String notifyUrl(Map<String, String> params, String out_trade_no,
			String trade_no, String trade_status, Float money) {
		// 先本地检查，看是否已经支付成功
				WisPayment livePaymentCheck = wisPaymentDao.selectCompleteByCode(out_trade_no);
				if (livePaymentCheck != null) {
					return "success";
				}
				if (AlipayNotify.verify(params)) {// 验证成功
					if (trade_status.equals("TRADE_FINISHED")|| trade_status.equals("TRADE_SUCCESS")) {
						WisPayment livePaymentExist = wisPaymentDao.selectWaitingByCode(out_trade_no);
						if (livePaymentExist == null|| livePaymentExist.getMoney().floatValue() != money.floatValue()) {
							return "fail";
						}
						WisPayment livePaymentUpdate = new WisPayment();
						livePaymentUpdate.setId(livePaymentExist.getId());
						livePaymentUpdate.setCompletionTime(wisPaymentDao.getTime());
						livePaymentUpdate.setStatusId(2);
						livePaymentUpdate.setPaymentMethod("alipay");
						livePaymentUpdate.setTradeNo(trade_no);
						int rows = wisPaymentDao.updateByPrimaryKeySelective(livePaymentUpdate);
						if (rows != 1) {
							return "fail";
						} else {
								WisSign wisSign=new WisSign();
								wisSign.setWisLessonId(livePaymentExist.getLiveInfoId());
								wisSign.setUserId(livePaymentExist.getUserId());
								wisSign.setRegisterTime(DateUtil.dateToString(new Date(), 2));
								wisSign.setDisableFlag(0);
								int rowss=wisSignDao.insert(wisSign);
								if(rowss!=1){
									return "fail";
								}else{
									return "success";
								}
							
						}
					} else {
						return "fail";
					}
			    }else {
			    	return "fail";
				}
	}
	
	
	@Override
	public String WXnotifyUrl(ScanPayResData scanPayResData) {
		// 先本地检查，看是否已经支付成功
				WisPayment livePaymentCheck = wisPaymentDao.selectCompleteByCode(scanPayResData.getOut_trade_no());
				if (livePaymentCheck != null) {
					//支付成功
					return "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
					        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
				}
				if("SUCCESS".equals(scanPayResData.getResult_code())){
					WisPayment livePaymentExist = wisPaymentDao.selectWaitingByCode(scanPayResData.getOut_trade_no());
					int total_fee = (int) (livePaymentExist.getMoney().floatValue()*100);
					if (livePaymentExist == null|| total_fee != scanPayResData.getTotal_fee()) {
						return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
								+ "<return_msg><![CDATA[金额不相等]]></return_msg>" + "</xml> ";
					}
					WisPayment livePaymentUpdate = new WisPayment();
					livePaymentUpdate.setId(livePaymentExist.getId());
					livePaymentUpdate.setCompletionTime(wisPaymentDao.getTime());
					livePaymentUpdate.setStatusId(2);
					livePaymentUpdate.setPaymentMethod("wxqrpay");
					int rows = wisPaymentDao.updateByPrimaryKeySelective(livePaymentUpdate);
					if (rows != 1) {
						return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
								+ "<return_msg><![CDATA[更新订单数据失败]]></return_msg>" + "</xml> ";
					} else {
						WisSign wisSign=new WisSign();
						wisSign.setWisLessonId(livePaymentExist.getLiveInfoId());
						wisSign.setUserId(livePaymentExist.getUserId());
						wisSign.setRegisterTime(DateUtil.dateToString(new Date(), 2));
						wisSign.setDisableFlag(0);
						int rowss=wisSignDao.insert(wisSign);
						if(rowss!=1){
							return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
									+ "<return_msg><![CDATA[更新订单数据失败]]></return_msg>" + "</xml> ";
						}else{
							//支付成功
							return "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
									+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
						}
					}
				}else {
					return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[支付失败]]></return_msg>" + "</xml> ";
				}
	}
	
	@Override
	public OrderInfo selectWaitingByCode(String Code) {
		WisPayment wisPayment = wisPaymentDao.selectWaitingByCode(Code);
		if (wisPayment == null) {
			wisPayment = new WisPayment();
			wisPayment.setCode(Code);
			wisPayment.setMessageString("fail");
		}
		if(wisPayment.getStatusId().intValue() != 1){
			wisPayment.setMessageString("fail");
		}
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setName(wisPayment.getName());
		orderInfo.setMoney(wisPayment.getMoney());
		orderInfo.setMessageString(wisPayment.getMessageString());
		return orderInfo;
	}
	@Override
	public OrderInfo doScanPayBusiness(String Code) {
		WisPayment wisPayment = wisPaymentDao.selectByCode(Code);
		if (wisPayment == null) {
			wisPayment = new WisPayment();
			wisPayment.setCode(Code);
			wisPayment.setMessageString("fail");
		}
		if(wisPayment.getStatusId().intValue() != 1){
			wisPayment.setMessageString("fail");
		}
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setName(wisPayment.getName());
		orderInfo.setMoney(wisPayment.getMoney());
		orderInfo.setCode(wisPayment.getCode());
		orderInfo.setMessageString(wisPayment.getMessageString());
		return orderInfo;
	}
	//订单显示
	@Override
	public Map<String, Object> livePaymentList(WisPayment wisPayment) {
		// TODO Auto-generated method stub
		Map<String,Object> map = new HashMap<String,Object>();
		if(wisPayment.getCode()!=null){
			wisPayment.setCode("%"+wisPayment.getCode()+"%");
		}
		if(wisPayment.getName()!=null){
			wisPayment.setName("%"+wisPayment.getName()+"%");
		}
		map.put("total", wisPaymentDao.countLivePayment(wisPayment));
		List<WisPayment> list = wisPaymentDao.queryPageLivePayment(wisPayment);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(WisPayment o:list){
			if (o.getOrderTime()!=null) {
				o.setOrderTimeString(format.format(o.getOrderTime()));
			}else {
				o.setOrderTimeString("");
			}
			if (o.getCompletionTime()!=null) {
				o.setCompletionTimeString(format.format(o.getCompletionTime()));
			}else {
				o.setCompletionTimeString("");
			}
		}
		map.put("rows",list);
		return map;
	}
	@Override
	public WisPayment countBySchoolMoney(WisPayment wisPayment) {
		// TODO Auto-generated method stub
		if(wisPayment.getStatusId()==null){
			wisPayment.setStatusId(2);
		}
		return wisPaymentDao.countBySchoolMoney(wisPayment);
	}
}
